package com.zhen.filter;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class CoreFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest req = (HttpServletRequest) servletRequest;
        HttpServletResponse resp = (HttpServletResponse) servletResponse;

        HttpSession session = req.getSession();
        Object uid = session.getAttribute("UID");
        String requestURI = req.getRequestURI();
        if("/zhen/login.jsp".equals(requestURI)||requestURI.endsWith(".css")||requestURI.endsWith(".js")||requestURI.endsWith(".png")){
            filterChain.doFilter(servletRequest,servletResponse);
            return;
        }
        if(uid==null){
            resp.sendRedirect("/zhen/login.jsp");
            System.out.println(requestURI+"页面被CoreFilter拦截，原因：uid is null");
            System.out.println("重定向到：/zhen/login.jsp");
            return;
        }
        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void destroy() {

    }
}
